package initialize

import (
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"main.go/global"
	"main.go/middleware"
	"main.go/router"
)

type justFilesFilesystem struct {
	fs http.FileSystem
}

func (fs justFilesFilesystem) Open(name string) (http.File, error) {
	f, err := fs.fs.Open(name)
	if err != nil {
		return nil, err
	}

	stat, _ := f.Stat()
	if stat.IsDir() {
		return nil, os.ErrPermission
	}

	return f, nil
}

// 初始化总路由

func Routers() *gin.Engine {
	Router := gin.New()
	// Router.Use(middleware.GinRecovery(true))
	if gin.Mode() == gin.DebugMode {
		Router.Use(gin.Logger())
		// Router.Use(middleware.DefaultLogger())
	}
	Router.Use(middleware.OperationRecord())

	Router.StaticFS(global.EVA_CONFIG.Local.StorePath, justFilesFilesystem{http.Dir(global.EVA_CONFIG.Local.StorePath)})
	// Router.Use(middleware.LoadTls())  // 如果需要使用https 请打开此中间件 然后前往 core/server.go 将启动模式 更变为 Router.RunTLS("端口","你的cre/pem文件","你的key文件")
	// 跨域，如需跨域可以打开下面的注释
	// Router.Use(middleware.Cors()) // 直接放行全部跨域请求
	// Router.Use(middleware.CorsByRules()) // 按照配置的规则放行跨域请求
	//global.GVA_LOG.Info("use middleware cors")
	// 方便统一添加路由组前缀 多服务器上线使用

	PublicGroup := Router.Group(global.EVA_CONFIG.System.RouterPrefix)
	{
		// 健康监测
		PublicGroup.GET("/health", func(c *gin.Context) {
			c.JSON(http.StatusOK, "ok")
		})
	}

	systemGroup := PublicGroup.Group("/system")
	//管理端路哟呀
	systemRouter := router.RouterGroupApp.System
	{
		systemRouter.InitUserRouter(systemGroup)
		systemRouter.InitUploadFileRouter(systemGroup)
	}

	mallGroup := PublicGroup.Group("/mall")
	//客户端路由
	mallRouter := router.RouterGroupApp.Mall
	{
		mallRouter.InitUserRouter(mallGroup)
		mallRouter.InitOrderRouter(mallGroup)
		mallRouter.InitGoodsInfoRouter(mallGroup)
		mallRouter.InitGoodsCategoryRouter(mallGroup)
	}

	wechatGroup := PublicGroup.Group("/wechat")
	wechatRouter := router.RouterGroupApp.Wechat

	{
		wechatRouter.InitUserRouter(wechatGroup)
	}

	global.EVA_LOG.Info("router register success")
	return Router
}
